package com.easylinkin.linkappapi.openapi.util;

import javax.servlet.http.HttpServletRequest;
import eu.bitwalker.useragentutils.UserAgent;

public class IpUtil {
  
  public static UserAgent getUserAgent(HttpServletRequest request) {
    UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
    return userAgent;
  }

  public static String getIPAddress(HttpServletRequest request) {
    String ip = null;

    //X-Forwarded-For：Squid 服务代理
    String ipAddress = request.getHeader("x-forwarded-for");
    if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("Proxy-Client-IP");
    }
    if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("WL-Proxy-Client-IP");
    }

    //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
    if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
      if(ipAddress.indexOf(",")>0){
          ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
      }
    }

    //还是不能获取到，最后再通过request.getRemoteAddr();获取
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ip = request.getRemoteAddr();
    }
    return "0:0:0:0:0:0:0:1".equals(ip)?"127.0.0.1":ip;
  }
}
